package com.tian.view

import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.button.MaterialButton

/**
 * @author tiansongtao, Email:tiansongtao@up366.com
 * @date 2022/12/13 14:45
 */
open class BaseRecyclerAdapter : RecyclerView.Adapter<BaseRecyclerAdapter.BaseViewHolder>() {


    companion object {
        const val TYPE_DEFAULT = -1000
        const val TYPE_COMMON_BUTTON = 1
    }

    var datas = mutableListOf<DataHolder>()
        set(value) {
            field = value
            this.notifyDataSetChanged()
        }

    var itemClickListener: OnItemClickListener? = null

    interface OnItemClickListener {
        fun onItemClick(dataHolder: DataHolder, position: Int)
    }

    data class DataHolder(var viewType: Int, var o: Any? = null, var o1: Any? = null, var o2: Any? = null)


    class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        init {
            if (itemView.layoutParams == null && itemView is ViewGroup) {
                if (itemView.childCount == 1) {
                    val lp = itemView.getChildAt(0).layoutParams
                    itemView.setLayoutParams(ViewGroup.LayoutParams(lp))
                }
            }
        }
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        return when (viewType) {
            TYPE_COMMON_BUTTON -> {
                val itemButton = MaterialButton(parent.context)
                itemButton.transformationMethod = null
                val lp =
                    RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                itemButton.layoutParams = lp
                BaseViewHolder(itemButton)
            }
            else -> {
                val itemButton = MaterialButton(parent.context)
                val lp =
                    RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                itemButton.layoutParams = lp
                BaseViewHolder(itemButton)
            }
        }
    }

    override fun getItemViewType(position: Int) = datas[position].viewType

    override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
        val dataHolder = datas[position]
        when (dataHolder.viewType) {
            TYPE_COMMON_BUTTON -> {
                dataHolder.o?.let { (holder.itemView as MaterialButton).text = it as String }
                itemClickListener?.let { itemClick ->
                    holder.itemView.setOnClickListener { itemClick.onItemClick(dataHolder, position) }
                }
            }
        }
    }

    override fun getItemCount() = datas.size
}